package com.dfec.water.util;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Base64;

/**
 * @author trg
 * @description: TODO
 * @title: Base64ToImageConverter
 * @projectName water-soil-conservation-serve
 * @email 1446232546@qq.com
 * @date 2025/2/25 10:01
 */
public class Base64ToImageConverter {

    public static void main(String[] args) {
        String base64Image = "your_base64_encoded_image_string"; // 替换为你的Base64编码字符串
        String outputImagePath = "path/to/output/image.png"; // 替换为你希望保存图片的路径

        try {
            convertBase64ToImage(base64Image, outputImagePath);
            System.out.println("图片已成功保存到: " + outputImagePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void convertBase64ToImage(String base64Image, String outputImagePath) throws IOException {
        // 去除Base64编码前的前缀，例如 "data:image/png;base64,"
        String imagePrefix = "data:image/png;base64,";
        if (base64Image.startsWith(imagePrefix)) {
            base64Image = base64Image.substring(imagePrefix.length());
        }

        // 解码Base64字符串为字节数组
        byte[] imageBytes = Base64.getDecoder().decode(base64Image);

        // 将字节数组转换为BufferedImage
        ByteArrayInputStream bais = new ByteArrayInputStream(imageBytes);
        BufferedImage image = ImageIO.read(bais);

        // 保存BufferedImage到文件
        File outputFile = new File(outputImagePath);
        String formatName = outputImagePath.substring(outputImagePath.lastIndexOf('.') + 1);
        ImageIO.write(image, formatName, outputFile);
    }
}
